using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Markup;
using Rhizome.Contract;
using Rhizome.Contract.Diag;
using Rhizome.Model.Validation;

namespace Rhizome.Model
{
	[ContentProperty("Action")]
	public abstract class ActiveTriggerBase<TPlant> : ActiveRuleBase<TPlant>, ITrigger
	{
		/// <summary>
		/// Trigger action (can be inherited from parent trigger)
		/// </summary>
		public virtual IAction Action
		{
			[DebuggerStepThrough]
			get { return GetValue(ActionProperty); }
			[DebuggerStepThrough]
			set { SetValue(ActionProperty, value); }
		}

		/// <summary>
		/// Optional trigger criterion (can be inherited from parent trigger)
		/// </summary>
		public ICriterion Criterion
		{
			[DebuggerStepThrough]
			get { return GetValue(CriterionProperty); }
			[DebuggerStepThrough]
			set { SetValue(CriterionProperty, value); }
		}

		protected void Trigged()
		{
			var criterion = Criterion;
			if (criterion == null || criterion.Test()) 
				Action.Process();
		}

		#region Implementation of IValidate

		public override IEnumerable<IValidationResult> GetValidationResults()
		{
			return 
				Action == null 
					? base.GetValidationResults().Concat(new[] {ValidationResult.ActionIsNull}) 
					: base.GetValidationResults();
		}

		#endregion

		public virtual object GetForwardEvent()
		{
			var forwardEvent = Action as IForwardEvent;
			return
				forwardEvent != null &&
				Criterion != null && Criterion.Test()
					? forwardEvent.GetForwardEvent()
					: null;
		}

		
	}
}